package cn.shenlong.common;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

public class ClobStringTypeHandler implements TypeHandler<String> {

	public void setParameter(PreparedStatement ps, int i, String parameter,
			JdbcType jdbcType) throws SQLException {
		byte[] byteArray = null;
		try {
			byteArray = parameter.getBytes("UTF-8");
		} catch (Exception e) {
			byteArray = new byte[] {};
		}
		ByteArrayInputStream bis = new ByteArrayInputStream(byteArray);
		ps.setBinaryStream(i, bis, byteArray.length);
	}

	public String getResult(ResultSet rs, String columnName)
			throws SQLException {
		String rtn = "";
		try {
			Clob clob = rs.getClob(columnName);
			rtn = clobToString(clob);
		} catch (Exception e) {
			rtn = "";
		}
		return rtn;
	}

	public String getResult(ResultSet rs, int columnIndex) throws SQLException {

		String rtn = "";
		try {
			Clob clob = rs.getClob(columnIndex);
			rtn = clobToString(clob);
		} catch (Exception e) {
			rtn = "";
		}
		return rtn;
	}

	public String getResult(CallableStatement cs, int columnIndex)
			throws SQLException {
		String rtn = "";
		try {
			Clob clob = cs.getClob(columnIndex);
			rtn = clobToString(clob);
		} catch (Exception e) {
			rtn = "";
		}
		return rtn;
	}

	private String clobToString(Clob clob) throws SQLException, IOException {
		String tmpStr = "";
		StringBuffer sb = new StringBuffer();
		BufferedReader br = new BufferedReader(clob.getCharacterStream());
		while ((tmpStr = br.readLine()) != null) {
			sb.append(tmpStr);
		}
		return sb.toString();
	}

}
